package jm.nj.demo22mian.apis;


import org.junit.Test;

import java.sql.*;

public class JdbcDemo_api6 {
    @Test
    public void demo() throws SQLException, ClassNotFoundException {
        //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2.连接数据库
        Connection conn = DriverManager.getConnection("jdbc:mysql:///day22","root","123456");

        //3.创建sql执行平台
        Statement stmt = conn.createStatement();

        //4.执行sql
        ResultSet rs = stmt.executeQuery("select *  from user ");

        //5.处理执行结果
        /*
        * java.sql.ResultSet：查询的结果集对象。相当于一个二维表，不同的是ResultSet自带一个行指针（游标）。游标默认指向头。
        * 使用rs.next()向下移动游标获取行， 返回true表示行有效，返回false表示行无效，到尾了//rs.next() trues false
        *  使用rs.previous()向上移动游标获取行， 返回true表示行有效，返回false表示行无效，到头了
        * rs.previous()
        * 使用rs.getXXX(columnIndex/columnName)获取列的数据。XXX表示数据类型；
        * rs.getXXX(columnlndex/columnName)
        * 参数：columnIndex:获取第几列的数据，从1开始
         * 		参数：columnName:字段的名称
        * */
        while(rs.next()){
            Integer uid = rs.getInt("uid");
            String username = rs.getString(2);
            String password = rs.getString("password");
            Double salary = rs.getDouble("salary");
            Integer age = rs.getInt("age");
            Date registTime = rs.getDate("registTime");
            Timestamp lastupdate = rs.getTimestamp("lastupdate");
            System.out.println(uid + "  " + username + "  " + password + "  " + salary + "  " +age + "  " + registTime + "  " + lastupdate);

        }
        while(rs.previous()){
            Integer uid = rs.getInt("uid");
            String username = rs.getString(2);
            String password = rs.getString("password");
            Double salary = rs.getDouble("salary");
            Integer age = rs.getInt("age");
            Date registTime = rs.getDate("registTime");
            Timestamp lastupdate = rs.getTimestamp("lastupdate");
            System.out.println(uid + "  " + username + "  " + password + "  " + salary + "  " +age + "  " + registTime + "  " + lastupdate);
        }
        //6.释放资源
        /**
         * 需要释放的资源有：ResultSet, Statement, Connection，三个对象都有close()方法用来释放资源
         * 释放的顺序：ResultSet --> Statement --> Connection
         */

        rs.close();
        stmt.close();
        conn.close();

    }
}
